package com.distribute.application.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.SrvApi;
import com.distribute.framework.model.SrvApiClient;
import com.distribute.framework.model.SrvApiType;

@RestController
@SuppressWarnings({"serial","unchecked"})
public class WikiController {
	
	@RequestMapping("/api/wiki/api.do")
	public Protocol api(){
		Protocol protocol = Protocol.create(true);
		List<SrvApiType> types = SrvApiType.where.satStatus(1).list(-1);
		protocol.set("apiTypes", types);
		if(Utils.getLong("api")!=null){
			SrvApi api = SrvApi.get(Utils.getLong("api"));
			protocol.set("srvApi",api.toJSON());
			protocol.set("list",SrvApi.where.saType(api.getSaType()).saStatusNot(2).list(-1),new BeanFormat<SrvApi>(){
				@Override
				public Map format(SrvApi arg0) {
					return arg0.toJSON();
				}
			});
		}else if(Utils.getLong("type")!=null){
			protocol.set("list",SrvApi.where.saType(Utils.getLong("type")).saStatusNot(2).list(-1),new BeanFormat<SrvApi>(){
				@Override
				public Map format(SrvApi arg0) {
					return arg0.toJSON();
				}
			});
			protocol.set("sort", SrvApiType.get(Utils.getLong("type")).toJSON());
		}
		return protocol;
	}
	
	@RequestMapping("/api/wiki/tools.do")
	public Protocol tools(){
		Protocol protocol = Protocol.create(true);
		List<SrvApiType> types = SrvApiType.where.satStatus(1).list(-1);
		protocol.set("apiTypes", types);
		if(Utils.getString("ajax")==null){
			SrvApi api = SrvApi.get(Utils.getLong("api"));
			if(api!=null){
				protocol.set("srvApi",api.toJSON());
			}
			protocol.set("list", SrvApi.list(Utils.add("saType",api==null?types.get(0).getSatId():api.getSaType()),-1),new BeanFormat<SrvApi>(){
				@Override
				public Map format(SrvApi arg0) {
					return arg0.toJSON();
				}
			});
			//获取系统分配的测试客户端帐号
			SrvApiClient testClient = SrvApiClient.where.sacClient("AE14").get();
			if(testClient!=null){
				protocol.set("testClient", testClient.toJSON());
			}
			return protocol;
		}else{
			if(Utils.getString("md5")!=null){
				protocol.set("md5", Utils.md5(Utils.getString("md5")).toUpperCase());
				return protocol;
			}else if(Utils.getLong("type")!=null){
				List<SrvApi> list = SrvApi.where.saType(Utils.getLong("type")).saStatus((short)1).list(-1);
				protocol.set("list",list,new BeanFormat<SrvApi>(){
					@Override
					public Map format(SrvApi arg0) {
						return arg0.toJSON();
					}
				});
				return protocol;
			}else if(Utils.getLong("api")!=null){
				protocol.set("srvApi", SrvApi.get(Utils.getLong("api")).toJSON());
				return protocol;
			}
			return protocol;
		}
	}

}